{% extends 'site/content.html' %}
{% load staticfiles %}

{% block extrahead %}
    <style type="text/css">
        .edit-form label {
            width: 140px;
            text-align: right;
            padding: 0px 5px;
        }

        .edit-form label.inline {
            width: auto;
        }

        .cell-formset-container input {
            width: 70px;
        }

        .map {
            width: 650px;
            height: 400px;
            border: 1px solid black;
        }

        #location-selector {
            padding-left: 145px;
            padding-bottom: 10px;
            /*display: none;*/
        }

        .errorlist {
            background-color: red;
            color: white;
        }
    </style>
{% endblock extrahead %}

{% block page-title %}
    Panel edycji stacji bazowej
{% endblock page-title %}

{% block content-title %}
    {% if base_station %}
        {{ base_station }} (ID: {{ base_station.id }})
    {% else %}
        Nowa stacja bazowa
    {% endif %}
{% endblock content-title %}

{% block main-content %}

    {% if messages %}
        {% for message in messages %}
            <div class="alert alert-{{ message.tags }}">
                {{ message }}
            </div>
        {% endfor %}
    {% endif %}

    <form action="" method="post" id="basestation-form" class="edit-form" role="form">
        {% csrf_token %}
        {{ form.non_field_errors }}

        <div>
            <label>ID</label>
            {{ base_station.id }}
        </div>

        {# location #}
        <div>
            {{ form.location.label_tag }}
            <span id="location-info">{{ base_station.location }}</span>
            (ID: <a href="{% if form.location.value %}{% url 'panel:location-edit-view' form.location.value %}{% endif %}" target="_blank" id="location-edit-url"><span id="location-id">{{ form.location.value|default_if_none:"" }}</span></a>)

            <button id="location-selector-toggler" class="btn btn-info">Wybierz z mapy</button><br/>
            {{ form.location }} {{ form.location.errors }}
        </div>

        {# location selector map #}
        <div id="location-selector">
            <input type="hidden" id="coords" value="{{ base_station.location_coords }}" />
            <input type="text" id="location-search" placeholder="Szukaj lokalizacji..." />
            <div id="location-map" class="map"></div>
        </div>

        {# location_details #}
        <div>
            {{ form.location_details.label_tag }}
            <input type="text" name="{{ form.location_details.html_name }}" id="{{ form.location_details.id_for_label }}" value="{{ form.location_details.value|default_if_none:"" }}" style="width: 500px;" />
            {{ form.location_details.errors }}
        </div>

        {# network & is_networks #}
        <div>
            {{ form.network.label_tag }}
            {{ form.network }}
            {{ form.network.errors }}
            <label class="inline">{{ form.is_networks }} NetWorks!</label>
            <label class="inline">{{ form.is_common_bcch }} Common BCCH</label>
        </div>

        {# station_id & rnc & enbi #}
        <div>
            {{ form.station_id.label_tag }}
            <input type="text" name="{{ form.station_id.html_name }}" id="{{ form.station_id.id_for_label }}" value="{{ form.station_id.value|default_if_none:"" }}" style="width: 80px;" />
            {{ form.station_id.errors }}

            {{ form.rnc.label_tag }}
            <input type="text" name="{{ form.rnc.html_name }}" id="{{ form.rnc.id_for_label }}" value="{{ form.rnc.value|default_if_none:"" }}" style="width: 80px;" />
            {{ form.rnc.errors }}

            {{ form.enbi.label_tag }}
            <input type="text" name="{{ form.enbi.html_name }}" id="{{ form.enbi.id_for_label }}" value="{{ form.enbi.value|default_if_none:"" }}" style="width: 80px;" />
            {{ form.enbi.errors }}
        </div>

        {# notes #}
        <div>
            {{ form.notes.label_tag }}
            <input type="text" name="{{ form.notes.html_name }}" id="{{ form.notes.id_for_label }}" value="{{ form.notes.value|default_if_none:"" }}" style="width: 500px;" /> {{ form.notes.errors }}
        </div>

        {# station_status & edit_status #}
        <div>
            {{ form.station_status.label_tag }}
            {{ form.station_status }}
            {{ form.station_status.errors }}

            {{ form.edit_status.label_tag }}
            {{ form.edit_status }}
            {{ form.edit_status.errors }}
        </div>

        {# date_added & date_updated #}
        <div>
            <label>Aktualizacja</label>
            {{ base_station.date_updated }}
            <label>Data dodania</label>
            {{ base_station.date_added }}
        </div>

        <h3>Komórki stacji bazowej</h3>

        <p><small>Pole LongCID jest generowane dynamicznie na podstawie wartości pól RNC/ENBID+CID.</small></p>

        {% if cell_formset %}
            {{ cell_formset.management_form }}
            {{ cell_formset.non_field_errors }}
            <table class="table table-hover table-condensed">
            <tbody>
                <tr>
                    <th>Standard</th>
                    <th>Pasmo</th>
                    <th>Potw.?</th>
                    <th>Nośna</th>
                    <th>LAC</th>
                    <th>CID/CLID</th>
                    <th>LongCID/ECID</th>
                    <th>Notatki</th>
                    <th>&nbsp;</th>
                </tr>
            {% for cell_form in cell_formset  %}
                <tr class="cell-formset-container">
                    <td>
                       {{ cell_form.standard }}
                       {{ cell_form.standard.errors }}
                    </td>
                    <td>
                       {{ cell_form.band }}
                       {{ cell_form.band.errors }}
                    </td>
                    <td>
                       {{ cell_form.is_confirmed }}
                       {{ cell_form.is_confirmed.errors }}
                    </td>
                    <td>
                       {{ cell_form.ua_freq }}
                       {{ cell_form.ua_freq.errors }}
                    </td>
                    <td>
                       {{ cell_form.lac }}
                       {{ cell_form.lac.errors }}
                    </td>
                    <td>
                       <input type="text" name="{{ cell_form.cid.html_name }}" id="{{ cell_form.cid.id_for_label }}" value="{{ cell_form.cid.value }}" title="{{ cell_form.cid.help_text }}" />
                       {{ cell_form.cid.errors }}
                    </td>
                    <td>
                        <input type="text" name="{{ cell_form.cid_long.html_name }}" id="{{ cell_form.cid_long.id_for_label }}" value="{{ cell_form.cid_long.value }}" title="{{ cell_form.cid_long.help_text }}" style="width: 100px;" readonly />
                        {{ cell_form.cid_long.errors }}
                    </td>
                    <td>
                        <input type="text" name="{{ cell_form.notes.html_name }}" id="{{ cell_form.notes.id_for_label }}" value="{% if cell_form.notes.value %}{{ cell_form.notes.value }}{% endif %}" style="width: 150px;"/>
                        {{ cell_form.notes.errors }}
                        {{ cell_form.id }}
                        {{ cell_form.base_station }}
                    </td>
                    <td>
                        {{ cell_form.DELETE }}
                        <a class="clone-row" href="javascript:void(0)">sklonuj</a>
                    </td>
                </tr>
            {% endfor %}
            </tbody>
            </table>
        {% else %}
            <p>Zachowaj podstawowe dane stacji aby dodać rekordy komórek.</p>
        {% endif %}

        <p>&nbsp;</p>

        <p>
            <input type="submit" value="Zachowaj" class="btn btn-primary btn-lg" />
            {% if base_station %}
                <a href="{% url 'panel:basestation-add-view' %}?location={{ base_station.location.id }}" class="btn btn-info">Dodaj nową stację w tej lokalizacji</a>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <a href="{% url 'panel:basestation-add-view' %}" class="btn btn-info">Dodaj nową stację</a>
                <a href="{% url 'panel:location-add-view' %}" class="btn btn-info">Dodaj nową lokalizację</a>
            {% endif %}
        </p>
    </form>

{% endblock main-content %}

{% block extrascripts %}
    {# https://code.google.com/p/django-dynamic-formset/ #}
    <script type="text/javascript" src="{% static 'libs/jquery.formset.js' %}"></script>
    <script type="text/javascript">

        $(function() {

            var validateDuplicateCells = function() {
                var cids = [];
                $("input[name$='-cid']").each(function(){
                    var idx = $(this).attr('name').split('-')[1];
                    var cid = $(this).val();
                    var std = $('#id_cells-'+idx+'-standard').val();
                    var key = std+cid;
                    if (cids.indexOf(key) > -1 && parseInt(cid) > 0) {
                        $(this).css('background-color', 'rgb(255, 136, 136)');
                    } else {
                        $(this).css('background-color', 'white');
                    }
                    cids.push(std+cid);
                });
            };

            var calculateLongCid = function(idx) {
                var std = $('#id_cells-'+idx+'-standard').val();
                var rnc = parseInt($('#id_rnc').val());
                var enbi = parseInt($('#id_enbi').val());
                var cid = parseInt($('#id_cells-'+idx+'-cid').val());
                var longcid = 0;
                if (std == 'UMTS' && rnc > 0) {
                    var longcid = rnc * 65536 + cid;
                } else if (std == 'LTE' && enbi > 0) {
                    var longcid = enbi * 256 + cid;
                }
                $('#id_cells-'+idx+'-cid_long').val(longcid);
            };

            var cellChangeEvents = function() {

                $('select[name*=standard]').on('change', function(e){
                    var idx = $(this).attr('name').split('-')[1];
                    calculateLongCid(idx);
                    validateDuplicateCells();
                });

                $("input[name$='-cid']").on('keyup', function(e){
                    var idx = $(this).attr('name').split('-')[1];
                    calculateLongCid(idx);
                    validateDuplicateCells();
                });

                $('#id_rnc').on('keyup', function(){
                    $('select[name*=standard]').each(function(){
                        var idx = $(this).attr('name').split('-')[1];
                        calculateLongCid(idx);
                    });
                    validateDuplicateCells();
                });

                $('#id_enbi').on('keyup', function(){
                    $('select[name*=standard]').each(function(){
                        var idx = $(this).attr('name').split('-')[1];
                        calculateLongCid(idx);
                    });
                    validateDuplicateCells();
                });

                $('.clone-row').on('click', function(){
                    $('.add-row').trigger('click');
                    // Traverse back to previous table cell and input field
                    var idx = $(this).parent('td').prev('td').find('input').attr('name').split('-')[1];
                    var idx_new = $('#id_cells-TOTAL_FORMS').val() - 1;
                    $("input[name^='cells-"+idx+"']").each(function(){
                        var target = $(this).attr('name').replace(idx, idx_new);
                        $("input[name='"+target+"']").val($(this).val());
                        if ($(this).is(':checked')) {
                            $("input[name='"+target+"']").attr('checked', true);
                        }
                    });
                    $("select[name^='cells-"+idx+"']").each(function(){
                        var target = $(this).attr('name').replace(idx, idx_new);
                        $("select[name='"+target+"']").val($(this).val());
                    });
                    $('input[name=cells-'+idx_new+'-cid]').focus();
                    validateDuplicateCells();
                });

                validateDuplicateCells();

            };

            $('.cell-formset-container').formset({
                prefix: '{{ cell_formset.prefix }}',
                keepFieldValues: "input",
                added: cellChangeEvents(),
                // removed: cellChangeEvents(),
                addText: 'dodaj komórkę',
                deleteText: 'usuń',
            });

            $('#location-selector-toggler').on('click', function(e){
                $('#location-selector').show();
                $('#location-selector-toggler').hide();
                e.preventDefault();
            });

        });
    </script>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;libraries=places"></script>
    <script type="text/javascript">
        $(function(){

            var map = null;
            var markers = [];
            var selectedIcon = "http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|ff0000|000000";
            var currentIcon = "http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|00ff00|000000";
            var normalIcon = "http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|ff776b|000000";
            var currentMarker;
            var selectedMarker = -1;
            var currentLocationId = $('#id_location').val();
            var selectedLocationId = -1;

            var handleMarkerClick = function(i, id) {
                google.maps.event.addListener(markers[i], 'click', function(){
                    if (currentMarker != i) {
                        if (selectedMarker >- 1) {
                            markers[selectedMarker].setIcon(normalIcon);
                        }
                        selectedMarker = i;
                        selectedLocationId = id;
                        markers[i].setIcon(selectedIcon);
                        var url = '/map/locations/' + id;
                        $.getJSON(url, function(data){
                            $('#location-info').html(data.summary);
                            $('#location-id').html(data.id);
                            $('#location-edit-url').attr('href', '/panel/location/' + data.id);
                            $('#id_location').val(data.id);
                        });
                    }
                });
            };

            var clearMap = function() {
                for (var i in markers) markers[i].setMap(null)
            };

            var getLocations = function() {
                var url = "/map/locations/?bounds=" + map.getBounds().toUrlValue() + '&empty';
                $.getJSON(url, function(data){
                    clearMap();
                    data = data.objects;
                    for (var i in data) {
                        var icon = normalIcon;
                        var locationId = data[i].id;
                        if (locationId == currentLocationId) {
                            icon = currentIcon;
                            currentMarker = i;
                        }
                        if (locationId == selectedLocationId) {
                            icon = selectedIcon;
                            selectedMarker = i;
                        }
                        markers[i] = new google.maps.Marker({
                            position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
                            icon: icon,
                            map: map
                        });
                        handleMarkerClick(i, locationId);
                    }
                });
            };

            var getInitLatLng = function() {
                var currentCoords = $('#coords').val();
                var coords = null;
                if (currentCoords) {
                    coords = currentCoords.split(',');
                } else {
                    coords = [52.069245, 19.480193]
                }
                return new google.maps.LatLng(coords[0],coords[1]);
            };

            var searchLocation = function(query) {
                var geocoder = new google.maps.Geocoder();
                var params = {
                    'address': query,
                    'region': 'pl'
                };
                geocoder.geocode(params, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(new google.maps.LatLng(
                            results[0].geometry.location.lat(),
                            results[0].geometry.location.lng()
                        ));
                    }
                });
            };

            var initParams = {
                zoom: 15,
                center: getInitLatLng(),
                streetViewControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            // Instantiate map object
            map = new google.maps.Map(document.getElementById("location-map"), initParams);

            // Attach event
            google.maps.event.addListener(map, 'idle', function() {
                if (map.getZoom() >= 11) {
                    getLocations();
                } else {
                    clearMap();
                }
            });

            $('#location-search').on('keypress', function(e){
                if (e.which == 13) {
                    searchLocation($(this).val());
                    e.preventDefault();
                }
            });

            searchBox = document.getElementById('location-search');
            autocomplete = new google.maps.places.Autocomplete(searchBox);
            autocomplete.bindTo('bounds', map);

            setTimeout(function(){
                $('#location-selector').hide();
            }, 1500);

        });
    </script>

{% endblock extrascripts %}